<template>
  <view class="activity-list">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="搜索活动名称、描述、地点或医院"
        @confirm="onSearch"
        @input="onSearch"
        radius="20"
        cancelButton="none"
      />
    </view>

    <!-- 医院筛选 -->
    <view class="hospital-filter" v-if="selectedHospital">
      <view class="filter-item">
        <uni-icons type="location" size="20" color="#007AFF"></uni-icons>
        <text class="filter-text">医院：{{ selectedHospital }}</text>
        <uni-icons 
          type="close" 
          size="20" 
          color="#999" 
          @click="clearHospitalFilter"
          style="margin-left: 10rpx;"
        ></uni-icons>
      </view>
    </view>

    <!-- 活动列表 -->
    <view class="activity-content">
      <uni-load-more 
        :status="loading ? 'loading' : 'more'" 
        :content-text="loading ? '加载中...' : '没有更多数据'"
      />
      
      <view v-if="!loading && filteredActivities.length === 0" class="empty-state">
        <uni-icons type="info" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无活动数据</text>
      </view>

      <view 
        v-for="activity in filteredActivities" 
        :key="activity.id" 
        class="activity-item"
      >
        <!-- 活动封面 -->
        <view class="activity-cover" v-if="activity.cover">
          <image 
            :src="getImageUrl(activity.cover)" 
            class="cover-image"
            mode="aspectFill"
            @error="onImageError"
          />
          <view class="status-badge" :class="getStatusClass(activity.status)">
            {{ getStatusText(activity.status) }}
          </view>
        </view>
        
        <!-- 活动信息 -->
        <view class="activity-info">
          <view class="activity-header">
            <text class="activity-name">{{ activity.name }}</text>
          </view>
          
          <view class="info-row">
            <uni-icons type="calendar" size="16" color="#666"></uni-icons>
            <text class="info-text">{{ formatDate(activity.startTime) }}</text>
          </view>
          
          <view class="info-row" v-if="activity.location">
            <uni-icons type="location" size="16" color="#666"></uni-icons>
            <text class="info-text">{{ activity.location }}</text>
          </view>
          
          <view class="info-row" v-if="activity.adminRealName">
            <uni-icons type="person" size="16" color="#666"></uni-icons>
            <text class="info-text">{{ activity.adminRealName }}</text>
          </view>
          
          <view class="info-row" v-if="activity.points">
            <uni-icons type="star" size="16" color="#FFD700"></uni-icons>
            <text class="info-text">积分奖励：{{ activity.points }}</text>
          </view>
        </view>
        
        <view class="activity-description" v-if="activity.description">
          {{ activity.description }}
        </view>
        
        <view class="activity-footer">
          <view class="activity-actions">
            <button 
              class="btn-detail" 
              @click="goToDetail(activity)"
            >
              查看详情
            </button>
            <button 
              class="btn-register" 
              @click="registerActivity(activity)"
              :disabled="!canRegister(activity)"
            >
              {{ getRegisterButtonText(activity) }}
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import request from '@/utils/request.js'
import tokenManager from '@/utils/token.js'

export default {
  name: 'ActivityList',
  setup() {
    const activities = ref([])
    const loading = ref(false)
    const searchKeyword = ref('')
    const selectedHospital = ref('')

    // 过滤后的活动列表
    const filteredActivities = computed(() => {
      let filtered = activities.value
      
      // 按医院筛选
      if (selectedHospital.value) {
        filtered = filtered.filter(activity => 
          activity.adminRealName === selectedHospital.value
        )
      }
      
      // 按关键词搜索
      if (searchKeyword.value) {
        filtered = filtered.filter(activity => 
          activity.name.includes(searchKeyword.value) ||
          (activity.description && activity.description.includes(searchKeyword.value)) ||
          (activity.location && activity.location.includes(searchKeyword.value)) ||
          (activity.adminRealName && activity.adminRealName.includes(searchKeyword.value))
        )
      }
      
      return filtered
    })

    // 获取活动列表
    const fetchActivities = async () => {
      loading.value = true
      try {
        console.log('开始获取活动列表...')
        const response = await request.request({
          url: '/activity/listWithAdmin',
          method: 'GET'
        })

        console.log('活动列表响应:', response)

        if (response.code === 200) {
          activities.value = response.data || []
          console.log('获取活动列表成功:', activities.value)
        } else {
          console.error('获取活动列表失败:', response)
          uni.showToast({
            title: response.message || '获取活动列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取活动列表错误:', error)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }

    // 搜索功能
    const onSearch = () => {
      // 实时搜索，不需要额外处理，computed会自动过滤
    }

    // 跳转到活动详情
    const goToDetail = (activity) => {
      uni.navigateTo({
        url: `/pages/activity/activity-detail?id=${activity.id}`
      })
    }

    // 预约活动
    const registerActivity = (activity) => {
      if (!tokenManager.isLoggedIn()) {
        uni.showModal({
          title: '提示',
          content: '请先登录后再预约活动',
          showCancel: false,
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            }
          }
        })
        return
      }

      // 跳转到预约页面
      uni.navigateTo({
        url: `/pages/activity/register?id=${activity.id}&name=${encodeURIComponent(activity.name)}`
      })
    }

    // 判断是否可以预约
    const canRegister = (activity) => {
      return activity.status === 'PENDING' || activity.status === 'ONGOING'
    }

    // 获取预约按钮文本
    const getRegisterButtonText = (activity) => {
      switch (activity.status) {
        case 'PENDING': return '立即预约'
        case 'ONGOING': return '预约参加'
        case 'COMPLETED': return '已结束'
        case 'CANCELLED': return '已取消'
        default: return '预约'
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '待定'
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    // 获取状态样式类
    const getStatusClass = (status) => {
      switch (status) {
        case 'PENDING': return 'status-pending'
        case 'ONGOING': return 'status-ongoing'
        case 'COMPLETED': return 'status-completed'
        case 'CANCELLED': return 'status-cancelled'
        default: return 'status-default'
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'PENDING': return '待开始'
        case 'ONGOING': return '进行中'
        case 'COMPLETED': return '已完成'
        case 'CANCELLED': return '已取消'
        default: return '未知'
      }
    }

    // 获取图片URL
    const getImageUrl = (coverPath) => {
      if (!coverPath) return ''
      if (coverPath.startsWith('http')) {
        return coverPath
      }
      // 如果是相对路径，需要拼接基础URL
      return `/api/file/download?filePath=${encodeURIComponent(coverPath)}`
    }

    // 图片加载错误处理
    const onImageError = (e) => {
      console.log('图片加载失败:', e)
    }

    // 清除医院筛选
    const clearHospitalFilter = () => {
      selectedHospital.value = ''
    }

    onMounted(() => {
      // 获取页面参数
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const options = currentPage.options
      
      if (options.hospital) {
        selectedHospital.value = decodeURIComponent(options.hospital)
      }
      
      fetchActivities()
    })

    return {
      activities,
      loading,
      searchKeyword,
      selectedHospital,
      filteredActivities,
      onSearch,
      goToDetail,
      registerActivity,
      canRegister,
      getRegisterButtonText,
      formatDate,
      getStatusClass,
      getStatusText,
      getImageUrl,
      onImageError,
      clearHospitalFilter
    }
  }
}
</script>

<style scoped>
.activity-list {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-bar {
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.hospital-filter {
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.filter-item {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  padding: 20rpx;
  border-radius: 20rpx;
}

.filter-text {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.activity-content {
  padding: 20rpx;
}

.activity-item {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.activity-cover {
  position: relative;
  height: 300rpx;
  background-color: #f0f0f0;
}

.cover-image {
  width: 100%;
  height: 100%;
}

.status-badge {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #fff;
  font-weight: bold;
}

.status-pending {
  background-color: #1890ff;
}

.status-ongoing {
  background-color: #52c41a;
}

.status-completed {
  background-color: #999;
}

.status-cancelled {
  background-color: #ff4d4f;
}

.status-default {
  background-color: #666;
}

.activity-info {
  padding: 30rpx 30rpx 20rpx 30rpx;
}

.activity-header {
  margin-bottom: 20rpx;
}

.activity-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.info-text {
  margin-left: 15rpx;
  font-size: 26rpx;
  color: #666;
}

.activity-description {
  padding: 0 30rpx 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.activity-footer {
  padding: 20rpx 30rpx 30rpx 30rpx;
  border-top: 1rpx solid #eee;
}

.activity-actions {
  display: flex;
  gap: 20rpx;
}

.btn-detail {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #f8f8f8;
  color: #666;
  border: 1rpx solid #ddd;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.btn-register {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #007AFF;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.btn-register:disabled {
  background-color: #ccc;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}
</style>
